//
//  ItemsViewController.m
//  Together
//
//  Created by Dawn on 12-12-18.
//  Copyright (c) 2012年 Dawn. All rights reserved.
//

#import "ItemsViewController.h"
#import "BdjCell.h"
#import "BdjmmCell.h"
#import "NetEasyCell.h"
#import "QiubaiCell.h"
#import "NetEasyContentViewController.h"

@interface ItemsViewController ()

@end

@implementation ItemsViewController
@synthesize dataArray;
@synthesize dataDict;

- (void) dealloc{
    self.dataArray = nil;
    self.dataDict = nil;
    if (request) {
        [request cancelRequest];
        request.delegate = nil;
    }
    _slimeView.delegate = nil;
    [super dealloc];
}


- (id) initWithDict:(NSDictionary *)dict{
    if (self = [super init]) {
        self.dataDict = [NSDictionary dictionaryWithDictionary:dict];
        
        // 数据文件夹路径
        NSString *cPath = [Common dataFilePath:[dict objectForKey:@"FileName"]];
        
        // 检测数据文件夹是否存在，如果不存在就创建
        if (![[NSFileManager defaultManager] fileExistsAtPath:cPath]){
            self.dataArray = nil;
        }else{
            NSData *data = [NSData dataWithContentsOfFile:cPath];
            NSDictionary *infoDict = [data objectFromJSONData];
            
            NSString *type = (NSString *)[self.dataDict objectForKey:@"Type"];
            if ([type isEqualToString:@"Bdj"]) {
                self.dataArray = (NSArray *)[infoDict objectForKey:@"list"];
            }else if([type isEqualToString:@"Bdjmm"]){
                self.dataArray = (NSArray *)[infoDict objectForKey:@"list"];
            }else if([type isEqualToString:@"NetEasy"]){
                self.dataArray = (NSArray *)[infoDict objectForKey:[dict objectForKey:@"FileName"]];
            }else if([type isEqualToString:@"Qiubai"]){
                self.dataArray = (NSArray *)[infoDict objectForKey:@"items"];
            }
        }
        
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    CGRect bounds = CGRectMake(0, 0, self.view.bounds.size.width, MAINCONTENTHEIGHT);
    _tableView = [[UITableView alloc] initWithFrame:bounds];
    bounds.size.height += 1;
    _tableView.contentSize = bounds.size;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    
    NSString *type = (NSString *)[self.dataDict objectForKey:@"Type"];
    if ([type isEqualToString:@"Bdj"]) {
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else if([type isEqualToString:@"Bdjmm"]){
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else if([type isEqualToString:@"NetEasy"]){
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }else if([type isEqualToString:@"Qiubai"]){
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 背景色
        UIView *tableViewBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MAINCONTENTHEIGHT)];
        UIImage *bgImage = [UIImage imageNamed:@"qiubai_background.png"];
        tableViewBgView.backgroundColor = [UIColor colorWithPatternImage:bgImage];
        
        _tableView.backgroundView = tableViewBgView;
        [tableViewBgView release];
    }
    
    _tableView.rowHeight = 70;
    [self.view addSubview:_tableView];
    [_tableView release];
    
    _slimeView = [[SRRefreshView alloc] init];
    _slimeView.delegate = self;
    _slimeView.upInset = 0;
    
    [_tableView addSubview:_slimeView];
    [_slimeView release];
    
    self.title = [self.dataDict objectForKey:@"Title"];
}

#pragma mark -
#pragma mark NewsRequestDelegate
- (void) requestFailed:(NewsRequest *)rst{
    [_slimeView endRefresh];
    request = nil;
}

- (void) requestFinished:(NewsRequest *)rst withData:(NSDictionary *)dict{
    [_slimeView endRefresh];
    NSString *type = (NSString *)[self.dataDict objectForKey:@"Type"];
    if ([type isEqualToString:@"Bdj"]) {
        self.dataArray = (NSArray *)[dict objectForKey:@"list"];
    }else if([type isEqualToString:@"Bdjmm"]){
        self.dataArray = (NSArray *)[dict objectForKey:@"list"];
    }else if([type isEqualToString:@"NetEasy"]){
        self.dataArray = (NSArray *)[dict objectForKey:[self.dataDict objectForKey:@"FileName"]];
    }else if([type isEqualToString:@"Qiubai"]){
        self.dataArray = (NSArray *)[dict objectForKey:@"items"];
    }
    [_tableView reloadData];
    request = nil;
}

#pragma mark - slimeRefresh delegate

- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView{
    
    NSString *urlString = [self.dataDict objectForKey:@"API"];
    NSURL *url = [NSURL URLWithString:urlString];
    request = [NewsRequest requestWithURL:url];
    request.index = 2;
    request.delegate = self;
    request.saveName = [self.dataDict objectForKey:@"FileName"];
    
    NSString *type = (NSString *)[self.dataDict objectForKey:@"Type"];
    if ([type isEqualToString:@"Bdj"]) {
        request.newsType = Budejie;
    }else if([type isEqualToString:@"Bdjmm"]){
        request.newsType = BudejieMM;
    }else if([type isEqualToString:@"NetEasy"]){
        request.newsType = NetEasyHeadline;
    }else if([type isEqualToString:@"Qiubai"]){
        request.newsType = Qiubai;
    }
    
    
    [request startRequest];
}

#pragma mark -
#pragma UITableViewDataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataArray) {
        return dataArray.count;
    }else{
        return 0;
    }
}


- (float) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *type = (NSString *)[self.dataDict objectForKey:@"Type"];
    if ([type isEqualToString:@"Bdj"]) {
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        NSString *text = [dict objectForKey:@"text"];
        CGSize size = CGSizeMake(SCREEN_WIDTH - 20, 10000);
        size = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
        
        CGSize imageSize = CGSizeMake([[dict objectForKey:@"width"] intValue], [[dict objectForKey:@"height"] intValue]);
        
        float width =  MIN(imageSize.width, SCREEN_WIDTH - 20);
        float height =  MIN(imageSize.height, width * imageSize.height / imageSize.width);
       
        return size.height + 20 + 10 + height + 10;
    }else if([type isEqualToString:@"Bdjmm"]){
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        NSString *text = [dict objectForKey:@"text"];
        CGSize size = CGSizeMake(SCREEN_WIDTH - 20, 10000);
        size = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
        return size.height + 20 + 12 + 40;
    }else if([type isEqualToString:@"NetEasy"]){
        return 70;
    }else if([type isEqualToString:@"Qiubai"]){
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        NSString *text = [dict objectForKey:@"content"];
        CGSize size = CGSizeMake(SCREEN_WIDTH - 20, 10000);
        size = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
        if ([dict objectForKey:@"image"] && [dict objectForKey:@"image"] != [NSNull null]) {
            return size.height + 20 + 10 + SCREEN_WIDTH;

        }else{
            return size.height + 20 + 10 + 10+ 10;
        }
    }

    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *type = (NSString *)[self.dataDict objectForKey:@"Type"];
    if ([type isEqualToString:@"Bdj"]) {
        BdjCell *cell = (BdjCell *)[tableView dequeueReusableCellWithIdentifier:@"BdjCell"];
        if (!cell) {
            cell = [[[BdjCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BdjCell"] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        [cell setName:[dict objectForKey:@"screen_name"]];
        NSDate *date = [Common nsDateFromDateString:[dict objectForKey:@"addtime"]];
        [cell setTime:[Common dateSwitchFromDate:date]];
        [cell setContent:[dict objectForKey:@"text"]];
        
        if ([dict objectForKey:@"image1"] && [dict objectForKey:@"image1"] != [NSNull null]) {
            NSString *imageUrlStr = [dict objectForKey:@"image1"];
            if (![imageUrlStr isEqualToString:@""]) {
                NSURL *url = [NSURL URLWithString:imageUrlStr];
                CGSize imageSize = CGSizeMake([[dict objectForKey:@"width"] intValue], [[dict objectForKey:@"height"] intValue]);
                BOOL isGif = [[dict objectForKey:@"is_gif"] boolValue];
                
                [cell setImageWithURL:url imageSize:imageSize isGif:isGif];
            }
        }
        
        return cell;
    }else if([type isEqualToString:@"Bdjmm"]){
        BdjmmCell *cell = (BdjmmCell *)[tableView dequeueReusableCellWithIdentifier:@"BdjmmCell"];
        if (!cell) {
            cell = [[[BdjmmCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BdjmmCell"] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        [cell setName:[dict objectForKey:@"name"]];
        NSDate *date = [Common nsDateFromDateString:[dict objectForKey:@"addtime"]];
        [cell setTime:[Common dateSwitchFromDate:date]];
        [cell setContent:[dict objectForKey:@"text"]];
        [cell setSex:[dict objectForKey:@"tag"]];
        return cell;
    }else if([type isEqualToString:@"NetEasy"]){
        NetEasyCell *cell = (NetEasyCell *)[tableView dequeueReusableCellWithIdentifier:@"NetEasyCell"];
        if (!cell) {
            cell = [[[NetEasyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NetEasyCell"] autorelease];
        }
        if (indexPath.row == 0) {
            [cell setSeparateViewHidden:YES];
        }else{
            [cell setSeparateViewHidden:NO];
        }
        
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        if ([dict objectForKey:@"imgsrc"] && [dict objectForKey:@"imgsrc"]!=[NSNull null] && ![[dict objectForKey:@"imgsrc"] isEqualToString:@""]) {
            [cell setNewsImageWithURL:[NSURL URLWithString:[dict objectForKey:@"imgsrc"]]];
        }else{
            [cell setNewsImageWithURL:nil];
        }
        [cell setTitle:[dict objectForKey:@"title"]];
        [cell setTips:[dict objectForKey:@"digest"]];
        NSDate *date = [Common nsDateFromDateString:[dict objectForKey:@"ptime"]];
        [cell setPub:[Common dateSwitchFromDate:date]];
        return cell;
    }else if([type isEqualToString:@"Qiubai"]){
        QiubaiCell *cell = (QiubaiCell *)[tableView dequeueReusableCellWithIdentifier:@"QiubaiCell"];
        if (!cell) {
            cell = [[[QiubaiCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"QiubaiCell"] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        if ([dict objectForKey:@"user"] && [dict objectForKey:@"user"] != [NSNull null]) {
            [cell setName:[[dict objectForKey:@"user"] objectForKey:@"login"]];
        }
        
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[dict objectForKey:@"created_at"] longLongValue]];
        [cell setTime:[Common dateSwitchFromDate:date]];
        [cell setContent:[dict objectForKey:@"content"]];
        
        if ([dict objectForKey:@"image"] && [dict objectForKey:@"image"] != [NSNull null]) {
            NSString *imageUrlStr = [dict objectForKey:@"image"];
            if (![imageUrlStr isEqualToString:@""]) {
                NSString *id = (NSString *)[dict objectForKey:@"id"];
                imageUrlStr = [NSString stringWithFormat:@"%@%@/%@/small/%@",QIUBAIIMAGEPATH,[id substringToIndex:4],id,[dict objectForKey:@"image"]];
                NSURL *url = [NSURL URLWithString:imageUrlStr];
                CGSize imageSize = CGSizeMake(SCREEN_WIDTH,SCREEN_WIDTH);
                
                [cell setImageWithURL:url imageSize:imageSize];
            }else{
                [cell setImageWithURL:nil imageSize:CGSizeMake(0, 0)];
            }
        }else{
            [cell setImageWithURL:nil imageSize:CGSizeMake(0, 0)];
        }
        
        return cell;
    }
    
    return nil;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *type = (NSString *)[self.dataDict objectForKey:@"Type"];
    if ([type isEqualToString:@"Bdj"]) {

    }else if([type isEqualToString:@"Bdjmm"]){
        
    }else if([type isEqualToString:@"NetEasy"]){
        NSDictionary *dict =  (NSDictionary *)[self.dataArray objectAtIndex:indexPath.row];
        NSString *urlString = [NSString stringWithFormat:@"%@%@/full.html",NETEASYCONTENT,[dict objectForKey:@"docid"]];
        NetEasyContentViewController *contentVC = [[NetEasyContentViewController alloc] initWithURL:urlString docid:[dict objectForKey:@"docid"]];
        contentVC.title = [self.dataDict objectForKey:@"Title"];
        [self.navigationController pushViewController:contentVC animated:YES];
        [contentVC release];
    }else if([type isEqualToString:@"Qiubai"]){

    }
}

#pragma mark -
#pragma UITableViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_slimeView scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_slimeView scrollViewDidEndDraging];
}

@end
